<template>
    <div>
        <el-card>
            <div style="display: flex; align-items: center; gap: 16px">
                <el-avatar :src="fullUrl(user?.profile?.avatar)" size="large" />
                <div>
                    <h3>{{ user?.username }}</h3>
                    <div>{{ user?.email }}</div>
                </div>
            </div>
        </el-card>

        <el-card style="margin-top: 16px">
            <h3>Your uploaded files</h3>
            <file-upload @uploaded="refreshList" />
            <el-table :data="files" style="width: 100%; margin-top: 12px">
                <el-table-column prop="name" label="Name" />
                <el-table-column prop="data_type" label="Type" />
                <el-table-column prop="visibility" label="Visibility" />
                <el-table-column label="Download" width="140">
                    <template #default="{ row }">
                        <el-button size="small" type="primary" @click="download(row)">Download</el-button>
                    </template>
                </el-table-column>
            </el-table>
        </el-card>
    </div>
</template>

<script setup lang="ts">
    import { ref, onMounted } from 'vue';
    import { get, post } from '@/axios/api';
    import { useAuth } from '@/common/useAuth';
    import FileUpload from '@/components/FileUpload.vue';
    import { fullUrl } from '@/common/util';
    import { ElMessage } from 'element-plus';

    const { user } = useAuth();
    const files: any = ref([]);

    async function refreshList() {
        const res = await get('files/');
        files.value = res;
    }

    async function download(row: any) {
        // call protected endpoint to get redirect or stream
        const url = 'files/' + row.id + '/download/';

        try {
            const token = localStorage.getItem('access_token'); // 或从你的 auth state 取
            const resp:any = await get(url, {
                responseType: 'blob',
                headers: token ? { Authorization: `Bearer ${token}` } : undefined
            });

            const blob = new Blob([resp]);
            const downloadName = row.name || 'download';
            const href = URL.createObjectURL(blob);
            const a = document.createElement('a');
            a.href = href;
            a.download = downloadName;
            document.body.appendChild(a);
            a.click();
            a.remove();
            URL.revokeObjectURL(href);
        } catch (err: any) {
            console.error('download error', err);
            // 如果是 404/401，给用户友好提示
            if (err?.response?.status === 401) {
                ElMessage.error('未登录或会话过期，请重新登录');
                // redirect to login if needed
            } else if (err?.response?.status === 403) {
                ElMessage.error('无权下载该文件');
            } else if (err?.response?.status === 404) {
                ElMessage.error('文件不存在（服务器返回 404）');
            } else {
                ElMessage.error('下载失败，请重试');
            }
        }

        // const a = document.createElement('a');
        // a.href = row.download_url; // our download_url calls protected endpoint which returns file
        // a.target = '_blank';
        // document.body.appendChild(a);
        // a.click();
        // a.remove();
    }
    
    onMounted(refreshList);
</script>
